/* eslint no-dupe-keys: 0, no-mixed-operators: 0 */
import React, { useState,useEffect } from 'react';
import {connect} from 'react-redux'
import {NewsAction} from '../../../store/actions'
import {get_newscountry,get_country_news,get_othercountry_news} from '../../../network/news'

import { ListView ,Toast , List ,Icon , Drawer , NavBar  } from 'antd-mobile';
import {Spin} from 'antd'

import {check_login} from '../../../tool'

import country from '../../../statics/img/country.svg'
import {country_img} from '../people/utils'

import './news.css'


const Home = (props) =>{

  const [major_country,setmajor_country] = useState([])
  const [isloading,setisloading] = useState(true)
  const [islistLoading,setislistloding] = useState(false)
  const [isitemloading,setisitemloading] = useState(true)
  const [end,setend] = useState(false)

  const [open,setopen] = useState()
  const [current_city_flag,setcurrent_city_flag] = useState()
 
 

  const {news_city,news_list,hasNextPage,pageNum,nextPage,setnewsCity,setnewsInfo} = props
  

  const sidebar = (
    <Spin spinning={isloading}>
    <List>
    <List.Item 
          thumb={country}
          multipleLine
        >国家/城市
    </List.Item>
    {major_country.map((item, index) => {
      const onitemclick = () =>{
          
          const cities = [...major_country]
          cities.pop()
          const getcountrynews = async() => {
            setislistloding(true)
            if (item!=='其他')
              {
                var news_res = await get_country_news(item,0)
              }
            else {
              var news_res = await get_othercountry_news(cities,1)
            }
            const data = news_res.data
            const list_info = {
              hasNextPage:data.pageable.paged,
              list : data.content,
              pageNum:data.number,
              nextPage:data.number+1
            }
            setnewsInfo(list_info)
            setislistloding(false)
          }
          setnewsCity(item)
    
          setcurrent_city_flag(country_img(item))
          setopen(false)
          getcountrynews()
      }
      return (<List.Item key={index}
        onClick = {onitemclick} 
        thumb={country_img(item)}
      >{item}</List.Item>);
    })}
  </List>
  </Spin>);

 

  const onOpenChange = () => {
    setopen(!open);
  }

  useEffect(()=>{
    
    if(news_city) setopen(false)
    else setopen(true)
   const get_news_country = async()=>{
      const country_res = await get_newscountry()
      try{
        setmajor_country([...country_res.data,'其他'])
        setisloading(false)
      }catch(err){
        console.log('跨域');
        setmajor_country(['暂无'])
        setisloading(false)
      }
      
    }

    if(check_login(props.identity))
    {
      get_news_country()
    }
    else {
      Toast.info('请先登录',2,()=>{  
        props.history.push({pathname:'/main/profile'})
    })
    }

    return (()=>{
      
    })
  },[])


  const dataSource = new ListView.DataSource({
          rowHasChanged: (row1, row2) => row1 !== row2,
        });

  const onitemclick = (value) =>{
    props.history.push({pathname:'news/detail',state:{newsinfo:value}})
  }

  const row = (item,_,i) => {

        return (    
            
          <div key={i} className ="item" onClick={()=>onitemclick(item)}>
            <div className="item_title">{item.chtitle}</div>
            <div className="item_content" >
                
              <div style={{ lineHeight: 2 }}>
                <div className="item_content_ct">{item.chcontent}</div>
               
                <div className='item_content_foot'>
                  <span>{item.media} {item.author}({item.country}) {item.date}</span>
                </div>
              </div>
            </div>
            
          </div>
        )
      }
          
  const separator = (sectionId,row_num) => {
      
      return (
      <div 
        key ={row_num}
        className="divider"
      />)
      }

  const onEndReached = (pagenum,hasmore) => {
          
          const getcountrynews = async() => {
            if(news_city === '其他'){
              const cities = [...major_country]
              cities.pop()
              var news_res = await get_othercountry_news(cities,pagenum) 
            }
            else
              var news_res = await get_country_news(news_city,pagenum)
            const data = news_res.data

            const list_info = {
              hasNextPage:data.pageable.paged,
              list : [...news_list,...data.content],
              pageNum:data.number,
              nextPage:data.number+1
            }
           
            setnewsInfo(list_info)
            setisitemloading(false)
          }
            if(hasmore)
            {
              getcountrynews()
            }
            else{
              setend(true)
              setisitemloading(false)
            }
            
            
          
        }

  return(
    <div className='news-content' style={{height:'calc( 100vh - 94px )',overflow:'hidden'}}>
                <NavBar icon={<Icon type="ellipsis" />} onLeftClick={onOpenChange}>{news_city ? <div className="nav_title"><img src ={country_img(news_city)} /> {news_city} </div>:'请选择要关注的地区'}</NavBar>
                <Drawer
                    className="my-drawer"
                    style={{ minHeight: document.documentElement.clientHeight }}
                    enableDragHandle 
                    contentStyle={{ color: '#A6A6A6', textAlign: 'center',  }}
                    sidebar={sidebar}
                    open={open}
                    onOpenChange={onOpenChange}
                >
                  { Array.isArray(news_list) === true ? 
                   <Spin spinning = {islistLoading}>       
                      <ListView
                      
                      dataSource={dataSource.cloneWithRows(news_list)}
                      initialListSize={10}
                      pageSize={15}
                      renderFooter={() => (<div style={{ padding: 30, textAlign: 'center' }}>
                        <Spin spinning={isitemloading}>
                        {end === true ? <div>暂无更多</div>:null}
                        </Spin>
                      </div>)}
                    
                      // renderBodyComponent={() => <MyBody />}
                      renderRow={(rowData,id1,i)=>row(rowData,id1,i)}
                      renderSeparator={separator}
                      style={{
                        position:'absolute',
                        width:'100vw',
                        height:'calc(100vh - 139px)',
                        overflow:'auto' ,            
                      }}
                      pageSize={4}
                      onScroll={() => { }}
                      // scrollRenderAheadDistance={500}
                      
                      onEndReached={()=>onEndReached(nextPage,hasNextPage)}
                      onEndReachedThreshold={15}
                    />
                            
                          
                  </Spin>
                
                :<div>请选择国家/地区</div>
                   
                }  
                </Drawer>
                
                </div>
  )
    
}




const mapState2Props = (state) => 
    ({
               
    identity : state.getIn(['login','identity']),
    news_city : state.getIn(['news','city']),
    hasNextPage : state.getIn(['news','hasNextPage']),          
    news_list : state.getIn(['news','news_list']),          
    pageNum : state.getIn(['news','pageNum']),          
    nextPage : state.getIn(['news','nextPage']),           
    })

const mapDispatch2Props = {
  setnewsCity : NewsAction.setnewsCity,
  setnewsInfo : NewsAction.setnewsInfo
}
                 

export default connect(mapState2Props,mapDispatch2Props )(Home)

